package soul.web.resource;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import soul.web.vo.FormAddUser;
import soul.web.vo.FormIdentify;
import soul.web.vo.Response;

import javax.validation.Valid;

@Controller
@RequestMapping("/user")
public class SUserResource {
    private static Logger LOGGER = LoggerFactory.getLogger(SUserResource.class);

    @Autowired
    private IdentityService identityService;

    @RequestMapping("/register")
    @ResponseBody
    public Response register(@RequestBody @Valid FormAddUser form) {

        LOGGER.info("注册---开始");
        User registerUser = form.toDomain();
        if (identityService.createUserQuery().userId(registerUser.getId()).singleResult() != null) {
            return Response.fail("用户名已存在");
        }
        identityService.newUser(registerUser.getId());
        identityService.saveUser(registerUser);
        LOGGER.info("注册---结束");
        return Response.ok();
    }

    @RequestMapping("/login")
    @ResponseBody
    public Response login(@RequestBody @Valid FormIdentify form) {
        LOGGER.info("登录---开始");
        UserEntity userEntity = form.toDomain();
        if(!identityService.checkPassword(userEntity.getFirstName(),userEntity.getPassword())) {
            return Response.fail("用户名密码错误");
        }
        LOGGER.info("登录---结束");
        return Response.ok();
    }
}
